package org.dylan.bdf.system.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.dylan.bdf.system.entity.Role;
import org.dylan.bdf.system.entity.User;
import org.dylan.bdf.system.service.SystemService;
import org.dylan.common.model.BaseQueryParam;
import org.dylan.common.model.BaseQueryParam.MatchType;
import org.dylan.common.paging.PageData;
import org.dylan.common.paging.PageRequest;
import org.dylan.core.util.Collections3;
import org.dylan.security.entity.IRole;
import org.dylan.security.service.PasswordService;
import org.dylan.security.util.SecurityUtils;
import org.dylan.web.model.JsonResult;
import org.dylan.web.plugin.omui.ModelConverter;
import org.dylan.web.plugin.omui.model.GridModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/system/user")
public class UserController {

	@Autowired
	private SystemService systemService;

	@Autowired
	private PasswordService passwordService;

	@RequestMapping(value = { "", "list" })
	public String list() {
		return "/system/user";
	}

	@RequestMapping("gridData")
	@ResponseBody
	public GridModel<User> gridData(HttpServletRequest request,
			@RequestParam(required = false) Integer start,
			@RequestParam(required = false) Integer limit,
			@RequestParam(required = false) Map<String, Object> params) {
		if (start == null) {
			start = 0;
		}
		if (limit == null) {
			limit = 15;
		}
		PageRequest pageRequest = new PageRequest(start, limit);
		pageRequest.addParam(new BaseQueryParam().field("username")
				.matchType(MatchType.LIKE_ANYWHERE)
				.value(params.get("username")));
		PageData<User> users = systemService.findUserByPage(pageRequest);
		GridModel<User> model = ModelConverter.convertToGridModel(users);
		return model;
	}
	
	@RequestMapping("userinfo")
	public String userinfo(ModelMap model){
		User loginUser = (User)SecurityUtils.getUser();
		User user = systemService.findUser(loginUser.getId());
		List<IRole> roles = user.getRoles();
		String roleNameList = Collections3.extractToString(roles, "name", ",");
		model.addAttribute("roleNameList", roleNameList);
		model.addAttribute("user", user);
		return "system/userinfo";
	}

	@RequestMapping("edit")
	public String edit(HttpServletRequest request,
			@RequestParam(required = false) String id, ModelMap model) {
		User user = null;
		if (StringUtils.isNotBlank(id)) {
			user = systemService.findUser(id);
			List<IRole> roles = user.getRoles();
			String roleIdList = Collections3.extractToString(roles, "id", ",");
			String roleNameList = Collections3.extractToString(roles, "name", ",");
			model.addAttribute("roleIdList", roleIdList);
			model.addAttribute("roleNameList", roleNameList);
		}
		model.addAttribute("user", user);
		return "system/user-form";
	}

	@RequestMapping("ajaxSave")
	@ResponseBody
	public JsonResult<String> ajaxSave(User user,
			@RequestParam(required = false) String roleIdList) {
		if (user.getDept() != null
				&& StringUtils.isBlank(user.getDept().getId())) {
			user.setDept(null);
		}
		if (StringUtils.isNotBlank(user.getId())) {// 修改用户信息
			User savedUser = systemService.findUser(user.getId());
			user.setPassword(savedUser.getPassword());
			user.setCreateTime(savedUser.getCreateTime());
			user.setCreateUser(savedUser.getCreateUser());
		} else {
			// 新增用户
			user.setPassword(passwordService.encryptPassword("111111"));
			user.setCreateTime(new Date());
			user.setCreateUser(SecurityUtils.getUser().getUsername());
		}
		// 角色信息
		List<IRole> roles = new ArrayList<IRole>();
		if (StringUtils.isNotBlank(roleIdList)) {
			for (String roleId : roleIdList.split(",")) {
				if (StringUtils.isNotBlank(roleId)) {
					Role role = new Role();
					role.setId(roleId.trim());
					roles.add(role);
				}
			}
		}
		user.setRoles(roles);
		systemService.saveUser(user);
		return JsonResult.str();
	}
	

	@RequestMapping(value="changePassword",method=RequestMethod.GET)
	public String changePassword(){
		return "system/changepassword";
	}
	
	@RequestMapping(value="changePassword",method=RequestMethod.POST)
	@ResponseBody
	public JsonResult<String> changePassword(String oldPassword,String newPassword,String confirmPassword) {
		JsonResult<String> result = new JsonResult<String>(false);
		User user = (User)SecurityUtils.getUser();
		if(!passwordService.passwordsMatch(oldPassword, user.getPassword())){
			result.setMsg("原密码输入有误！");
			return result;
		}
		else if(!StringUtils.equals(newPassword, confirmPassword)){
			result.setMsg("两次密码输入密码不一致！");
			return result;
		}
		systemService.changePassword(user,passwordService.encryptPassword(newPassword));
		return JsonResult.str();
	}
}
